package models

import (
	"fmt"
	"gvb-server/Request"
	"gvb-server/global"
	"gvb-server/utils"
	"time"
)

type Users struct {
	ID            uint               `gorm:"primaryKey" json:"id"`
	CreateDate    int64              `json:"create_date"`
	UpdateDate    int64              `json:"-"`
	NickName      string             `gorm:"size:30" json:"nick_name"` // 昵称
	UserName      string             `gorm:"size:30" json:"user_name"` // 用户名
	Password      string             `gorm:"size:64" json:"password"`
	Avatar        string             `gorm:"size:256" json:"avatar"`
	Email         string             `gorm:"size:128" json:"email"`
	Tel           string             `gorm:"size:18" json:"tel"`
	Addr          string             `gorm:"size:64" json:"addr"`
	Token         string             `gorm:"size:64" json:"token"`
	IP            string             `gorm:"size:20" json:"ip"`
	Role          uint               `gorm:"size:4;" json:"role"`
	DepartId      uint               `gorm:"size:4;" json:"depart_id"`
	SignSource    Request.SignSource `gorm:"type:smallint(6)" json:"sign_source"`
	ArticleModels []Article          `gorm:"foreignKey:UserID" json:"-"`
	CollectsModes []Article          `gorm:"many2many:user2_collects;joinForeignKey:UserID;JoinReferences:ArticleID" json:"-"`
	DeletedAt     int64              `json:"deleted_at"`
	Status        int                `gorm:"default:1" json:"status"`
}

type imgUser struct {
	UserId uint   `gorm:"user_id"`
	Name   string `gorm:"name"`
	Url    string `gorm:"url"`
}

// UserCreateData 新增修改
func UserCreateData(i Request.UserCreateRequest) (Pub utils.PubStatus) {
	Pub.Status = utils.ERROR

	var u Users
	var id uint
	var err error
	id = i.ID
	fmt.Println("id ============id \n", id)
	if id == 0 {
		err = global.DB.Take(&u, "user_name = ?", i.UserName).Error
		if err == nil {
			Pub.Status = 300
			Pub.Msg = "该用户已存在"
			return
		}
		if i.Password == "" || i.RePassword == "" {
			Pub.Msg = "请输入密码"
			return
		} else {
			u.Password = i.Password
		}
	}

	u.CreateDate = time.Now().Unix()
	u.UserName = i.UserName
	u.NickName = i.NickName
	u.Avatar = i.Avatar
	u.Email = i.Email
	u.Role = i.Role
	u.DepartId = i.DepId
	u.SignSource = i.SignSource
	u.Addr = i.Addr
	u.Tel = i.Tel
	u.Token = i.Token
	u.IP = i.IP

	// 开启事务
	tx := global.DB.Begin()
	if id == 0 {

		err = tx.Create(&u).Error
		Pub.Msg = "添加成功"
		id = u.ID
		if err != nil {
			tx.Rollback()
			return
		}

	} else {
		Pub.Msg = "修改成功"
		u.UpdateDate = time.Now().Unix()
		err = tx.Table("users").Where("id = ?", id).Updates(&u).Error
		if err != nil {
			tx.Rollback()
			return
		}
	}

	// 修改关联img
	var imgUsers []imgUser
	var imgUser imgUser
	for _, v := range i.Imgs {
		imgUser.UserId = id
		imgUser.Name = v.Name
		imgUser.Url = v.Url
		imgUsers = append(imgUsers, imgUser)
	}

	fmt.Printf("图片的======%#v", imgUser)

	err = tx.Table("user_img").Where("user_id = ?", id).Updates(map[string]interface{}{"status": 0, "deleted_at": time.Now().Unix()}).Error
	err = tx.Table("user_img").Create(&imgUsers).Error
	if err != nil {
		tx.Rollback()
		return
	}

	tx.Commit()
	Pub.Status = utils.SUCCESS
	return
}

func GetInfoById(id int) (user Users, err error) {
	err = global.DB.Model(Users{}).Where("id = ? ", id).First(&user).Error
	return
}

func UserDelByIds(s Request.UserDelRequest) {
	global.DB.Table("Users").Where("id IN ?", s.Ids).Updates(map[string]interface{}{"status": 0, "deleted_at": time.Now().Unix()})
}

func FindByName(username string) (user Users, err error) {
	err = global.DB.Model(Users{}).Where("username = ? and status = 1 ", username).First(&user).Error
	return
}
